<template>

<el-form ref="queryFormRef" :inline="true" :model="queryForm" >
    <el-form-item style="width: 240px" label="用户名称" prop="username" >
      <el-input v-model="queryForm.username" placeholder="username" />
    </el-form-item>
    <el-form-item  style="width: 240px" label="用户状态" prop="isvalid">
      <el-select
        v-model="queryForm.isvalid"
        placeholder="请选择用户状态"
      >
      <!-- 写死选项 不好
           动态数据 从数据库查 
      -->
        <el-option label="离职" value="0" />
        <el-option label="在职" value="1" />
        <el-option label="休假" value="2" />
        
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
      <el-button  @click="resetQuery">重置</el-button>
      <el-button type="primary" @click="addFormOpen">添加</el-button>
      <el-button type="primary" @click="deleteFormOpen">下岗</el-button>
    </el-form-item>
  </el-form>


      <el-table ref="tableRef" :data="tableList.tableData" height="500" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="uid" label="编号" width="80"/>
      <el-table-column prop="username" label="名称"  width="180"/>
      <el-table-column prop="password" label="密码"  width="180"/>
      <el-table-column prop="createUid" label="创建人"  width="80">
         <template #default="scope">
            <el-tag type="primary">{{scope.row.createUid }}</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="createUname" label="创建人名称"  width="180">
         <template #default="scope">
            <el-tag type="primary">{{scope.row.createUname }}</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="isvalid" label="用户状态"  width="80">
         <template #default="scope">
            <el-tag v-if="scope.row.isvalid == 0" type="info">离职</el-tag>
            <el-tag v-else-if="scope.row.isvalid == 1" type="success">在职</el-tag>
            <el-tag v-else-if="scope.row.isvalid == 2" type="warning">休假</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="loginTime" label="最后登录时间"  width="180">
         <template #default="scope">
            <el-tag type="success">{{scope.row.loginTime }}</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="regTime" label="注册时间"  width="180">
         <template #default="scope">
            <el-tag type="warning">{{scope.row.regTime }}</el-tag>
         </template>
      </el-table-column>
      <el-table-column prop="headImg" label="头像"  width="180">
         <template #default="scope">
            <img :src="scope.row.headImg">
         </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作"  width="180">
         <template #default="scope">
            <el-button @click="editFormOpen(scope.row.uid)" type="primary">修改</el-button>
            <el-button @click="authFormOpen(scope.row.uid)" type="primary">授权</el-button>
         </template>
      </el-table-column>

   </el-table>

   <el-pagination
      v-model:current-page="pageInfo.pageData.page"
      v-model:page-size="pageInfo.pageData.pageSize"
      :total="pageInfo.pageData.total"
      :page-sizes="[3, 6, 9]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />


    <el-dialog
    v-model="addDialogVisible"
    title="添加"
    width="400"
  >
  <el-form ref="addFormRef" :model="addForm" >
      <el-form-item label="用户名称" prop="username" >
         <el-input v-model="addForm.username" placeholder="username" />
      </el-form-item>
      <el-form-item  label="用户头像" prop="headImg" >
         <!-- <el-input v-model="addForm.headImg" placeholder="headImg" /> -->
         <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="myUpload"
            :before-upload="beforeAvatarUpload"
         >
            <img v-if="addForm.headImg" :src="addForm.headImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
         </el-upload>



      </el-form-item>
   </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="addFormSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>


  
  <el-dialog
    v-model="editDialogVisible"
    title="修改"
    width="400"
  >
  <el-form  :model="editForm.editData" >
      <el-form-item label="用户编号" prop="uid" >
         <el-input disabled v-model="editForm.editData.uid" placeholder="uid" />
      </el-form-item>
      <el-form-item label="用户名称" prop="username" >
         <el-input v-model="editForm.editData.username" placeholder="username" />
      </el-form-item>
      <el-form-item label="用户密码" prop="password" >
         <el-input v-model="editForm.editData.password" placeholder="password" />
      </el-form-item>

      <el-form-item  style="width: 100%" label="用户状态" prop="isvalid">
      <el-select
        v-model="editForm.editData.isvalid"
        placeholder="请选择用户状态"
      >
        <el-option label="离职" :value="0" />
        <el-option label="在职" :value="1" />
        <el-option label="休假" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item  label="注册时间" prop="regTime" >
         <!-- <el-input v-model="editForm.editData.regTime" placeholder="regTime" /> -->
         <el-date-picker
            v-model="editForm.editData.regTime"
            type="datetime"
            placeholder="请选择"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
            />
      </el-form-item>

      <el-form-item  label="用户头像" prop="headImg" >
         <!-- <el-input v-model="editForm.editData.headImg" placeholder="headImg" /> -->
         <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="myUpload2"
            :before-upload="beforeAvatarUpload"
         >
            <img v-if="editForm.editData.headImg" :src="editForm.editData.headImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
         </el-upload>


      </el-form-item>


   </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="editFormSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-dialog
    v-model="authDialogVisible"
    title="授权"
    width="400"
  >
  <el-form ref="authFormRef" :model="authForm.authData" >
      <el-form-item label="用户编号" prop="uid" >
         <el-input v-model="authForm.authData.uid" disabled placeholder="uid" />
      </el-form-item>
      <el-form-item  label="用户菜单"  >
         <el-tree
               ref="treeRef"
               style="max-width: 600px"
               :data="treeList.treeData"
               show-checkbox
               default-expand-all
               node-key="mid"
               highlight-current
               :props="defaultProps"
            />
      </el-form-item>
   </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="authDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="authFormSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {ref,reactive,onMounted, nextTick} from 'vue'
import {get,post} from '@/myaxios'
import axios from 'axios'
import router from '@/router'
import {Edit,Histogram,SwitchButton} from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus';
//上传功能
//上传检测函数
const beforeAvatarUpload = (rawFile) => {
//   if (rawFile.type !== 'image/jpeg') {
//     ElMessage.error('必须是jpg')
//     return false
//   } else 
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('必须小于10M')
    return false
  }
  return true
}
//上传函数
const myUpload = async(rawFile)=>{
        //获取文件
        // 通过组件获取文件  rawFile
        console.log(rawFile.file);
        
        //生成form 把文件放入form
        var formData = new FormData;
        formData.append("myfile",rawFile.file);
      //使用post请求 发送formData
      //   //设置请求头 Content-Type: multipart/form-data;
      let resp = await axios.post("http://localhost:8080/baseProj/upDemo2",formData,{headers: {'Content-Type': 'multipart/form-data'}})
      //通过响应 给图片绑定变量赋值 显示图片预览
      addForm.headImg = resp.data.returnData;
      
}

//上传函数2
const myUpload2 = async(rawFile)=>{
        //获取文件
        // 通过组件获取文件  rawFile
        console.log(rawFile.file);
        
        //生成form 把文件放入form
        var formData = new FormData;
        formData.append("myfile",rawFile.file);
      //使用post请求 发送formData
      //   //设置请求头 Content-Type: multipart/form-data;
      let resp = await axios.post("http://localhost:8080/baseProj/upDemo2",formData,{headers: {'Content-Type': 'multipart/form-data'}})
      //通过响应 给图片绑定变量赋值 显示图片预览
      editForm.editData.headImg = resp.data.returnData;
      
}


//授权功能
//获取选中菜单时 要调用tree的函数
const treeRef = ref()
//树型菜单数据列表
const treeList = reactive({treeData:[]})
//设置自定义数据对应关系
const defaultProps = {
  children: 'subMenu',
  label: 'menuname',
}

//授权框打开关闭
const authDialogVisible = ref(false);
//授权框表单
const authForm = reactive({authData:{
   uid:''
   }
})
//授权开框
const authFormOpen = async(currentUid)=>{
   //开框显示uid
   authForm.authData.uid = currentUid

   authDialogVisible.value = true

   //查询树形菜单数据
   let resp = await get("users/listAllMenusForAuth",{uid:currentUid})
   console.log(resp.data.returnData);
   treeList.treeData = resp.data.returnData.allMenus
   //控制默认tree菜单选中
   treeRef.value.setCheckedKeys(resp.data.returnData.listMid, false)

}

//授权关框
const authFormSubmit = ()=>{
   authDialogVisible.value = false
   //获得tree选中的编号
   let listMidArr = treeRef.value.getCheckedKeys(true);
   let listMidStr = listMidArr.join(",")
   console.log(listMidStr);
   //发送的参数
   let params = {uid:authForm.authData.uid,listMid:listMidStr}

   //调用存储接口
   operationData("users/updateUserMenuList",params)

}



//删除功能
const deleteFormOpen = ()=>{
   let selectionRows =  tableRef.value.getSelectionRows();
   console.log(selectionRows);
   if(selectionRows.length>0){
      let listUidArr = [];

      selectionRows.forEach(userData => {
         listUidArr.push(userData.uid);
      });
      
      let listUidStr = listUidArr.join(",")
      console.log(listUidStr);
      //弹框提示是否确认删除
      ElMessageBox.confirm(
         `确认要下岗编号为:[${listUidStr}]数据么`,
         '警告',
         {
            confirmButtonText: '下岗',
            cancelButtonText: '取消',
            type: 'warning',
         }
      )
         .then(() => {
            //准备提交参数
            let paramForm = {listUid:listUidStr};
            //提交数据
            operationData("/users/deleteUser",paramForm)
         })
         .catch(() => {
            console.log("取消删除");
         
         })
   }else{
      ElMessage.warning("请先选择数据.....")
   }
   
}


//修改功能
//对话框打开关闭
const editDialogVisible = ref(false)
//数据对象
const editForm = reactive({editData:{
   uid:'',
   username:'',
   password:'',
   headImg:'',
   isvalid:'',
   regTime:''
}})

//修改开框
const editFormOpen = async(currentUid)=>{
   editDialogVisible.value = true

  let resp = await get("/users/getUserForUpdate",{uid:currentUid})
  editForm.editData = resp.data.returnData

}
//修改提交
const editFormSubmit = ()=>{
   editDialogVisible.value = false
   let params = editForm.editData;
   console.log(params);
    //添加修改删除 处理数据
    operationData("/users/update",params)

}


//添加功能
//添加表单对象
const addForm = reactive({
   username:'',
   headImg:''
})
//添加表单对象
const addFormRef = ref()

//控制开启关闭对话框的bol值
const addDialogVisible = ref(false)


//添加开框
const addFormOpen = ()=>{
   addDialogVisible.value = true
   //nextTick中的代码 延后渲染
   nextTick(()=>{
      //延后渲染清空表单
      addFormRef.value.resetFields()
   })
   

}
//添加提交
const addFormSubmit = async()=>{
   addDialogVisible.value = false
   let params = addForm;
   console.log(params);
   //添加修改删除 处理数据
   operationData("/users/add",params)

}


//查询功能
//查询表单
const queryForm = reactive({
   username:'',
   isvalid:''
})


//分页组件
const pageInfo = reactive({pageData:{
   page:1,
   pageSize:3,
   total:66
}})


//table数据
const tableList = reactive({tableData:[]})
//table对象
const tableRef  = ref()
//查询表单对象
const queryFormRef = ref()

//分页查询
//页码改变
const handleCurrentChange = (val)=>{
   //根据组件页码变化的数值 改变查询参数的page值
   pageInfo.pageData.page = val;
   //查询页码参数
   let params = pageInfo.pageData
   //查询表单参数
   let params2 = queryForm;
   let allParams = {...params,...params2};
   //查询
   queryData(allParams)
}
//每页记录数改变
const handleSizeChange = (val)=>{
   //根据组件页码变化的数值 改变查询参数的page值
   pageInfo.pageData.page = 1;
   pageInfo.pageData.pageSize = val;
   //查询页码参数
   let params = pageInfo.pageData
   //查询表单参数
   let params2 = queryForm;
   let allParams = {...params,...params2};
   //查询
   queryData(allParams)
}
//重置查询表单
const resetQuery = ()=>{
   queryFormRef.value.resetFields();
   queryData({})
}
//查询按钮查询
const querySubmit = ()=>{
   //查询表单参数
   let params = queryForm;
   //查询数据
   queryData(params)

}



//公共函数
//查询函数
const queryData = async(params)=>{
   let resp = await get('/users/queryList',params)
   if(resp.data.returnCode == 10000){
      //table赋值
      tableList.tableData = resp.data.returnData
      //分页组件赋值
      pageInfo.pageData = resp.data.pageInfo
   }
}
//添加修改删除 操作数据
const operationData = async(url,params)=>{
   let resp = await post(url,params);

   //弹窗执行结果
   if(resp.data.returnCode == 10020){
      ElMessage.success(resp.data.returnMsg);
   }else if(resp.data.returnCode == 10021){
      ElMessage.error(resp.data.returnMsg);
   }
   //刷新页面数据
   //查询页码参数
   let params1 = pageInfo.pageData
   //查询表单参数
   let params2 = queryForm;
   let allParams = {...params1,...params2};
   //查询
   queryData(allParams)
}
   

//钩子函数
//页面加载完成 准备初始数据
onMounted(()=>{
   queryData({})
})


</script>



<style scoped>
   img{
      width: 40%;
      height: 40%;
   }

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>